import java.awt.AWTException;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.SystemTray;
import java.awt.TrayIcon;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URL;
import java.util.ArrayList;

import javax.swing.ImageIcon;

public class odbcSysTray {
	
	private ArrayList<OdbcMenuItem> popupMenuItems = new ArrayList<OdbcMenuItem>();
	private TrayIcon trayIcon;
	
	public odbcSysTray(ArrayList<connectionObj> odbc, long timer) {
		
		SystemTray tray = SystemTray.getSystemTray();
		
		/*
		 * http://www.clker.com/clipart-cmdb.html
		 */
		URL imageURL = odbcSysTray.class.getResource("images/cmdb-hi.png");
		trayIcon = new TrayIcon ((new ImageIcon(imageURL)).getImage());
		trayIcon.setImageAutoSize(true);
		
		PopupMenu popup = new PopupMenu();
		
		try {
			tray.add(trayIcon);
		} catch (AWTException e) {
			e.printStackTrace();
		}
		
		//Create the PopupMenu
		for (connectionObj o : odbc) { 
			popupMenuItems.add(new OdbcMenuItem(o));
		}	
		
		for (OdbcMenuItem o : popupMenuItems) { 
			popup.add(o);
		}
		
		popup.addSeparator();
		
		MenuItem refreshItem = new MenuItem("Refresh"); 
		refreshItem.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				refresh();
			} 
				
		});
		
		popup.add(refreshItem);
		
		MenuItem exitItem = new MenuItem("Exit");
		exitItem.addActionListener(new ActionListener() { 
				@Override
				public void actionPerformed(ActionEvent e) {
					System.exit(0);
					
				}
			}
		);
		
		popup.add(exitItem);
		
		//Add the PopupMenu
		trayIcon.setPopupMenu(popup);
	
		//Check the connection Status (Infinite Loop, exit depends on ActionListener in OdbcMenuItem
		String msg;
		while (true) {
			for (OdbcMenuItem i : popupMenuItems) { 
				msg = i.refreshStatus();
				if (msg != null) 
					trayIcon.displayMessage("Status", msg, TrayIcon.MessageType.NONE);
			}
			try {
				Thread.sleep(timer*1000);
			} catch (InterruptedException e1) {
				e1.printStackTrace();
			}
		}
	}
	
	//Force a refrehs of the odbc connection status
	private void refresh() {
		String msg;
		for (OdbcMenuItem i : popupMenuItems) {
			msg = i.refreshStatus();
			if (msg != null) 
				trayIcon.displayMessage("Status", msg, TrayIcon.MessageType.NONE);
		}
	}
	
}
